package com.smiier.skin.receiver;

import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.RemoteViews;
import cn.o.app.io.INoProguard;
import cn.o.app.json.JsonDate;
import cn.o.app.json.JsonUtil;
import cn.skinapp.R;

import com.evan.common.handler.RequestHandler;
import com.evan.common.handler.callback.HandlerCallback;
import com.evan.common.utils.CacheCommon;
import com.evan.common.utils.CommonUtility;
import com.evan.common.utils.DeviceUtility;
import com.igexin.sdk.PushConsts;
import com.smiier.skin.ChatActivity;
import com.smiier.skin.MyTreatmentProjectActivity;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.extra.TreatementProjectExtra;
import com.smiier.skin.intercept.RequestTaskIntercept;
import com.smiier.skin.net.DoctorReserveDetailTask.DoctorReserveDetail;
import com.smiier.skin.net.DoctorReserveDetailTask.DoctorReserveDetailResponse;
import com.smiier.skin.net.DoctorReserveListTask.DoctorReserveItem;
import com.smiier.skin.net.UserSetTask;
import com.smiier.skin.net.UserSetTask.UserSetRequest;
import com.smiier.skin.net.entity.User;
import com.smiier.skin.util.GlobalSettings;
import com.smiier.skin.util.KeyValueUtil;
import com.smiier.skin.utils.DBUtil;
import com.smiier.skin.vo.TipMessageVo;

public class MessageReceiver extends BroadcastReceiver {
	public NotificationManager mNotificationManager;
	NotificationCompat.Builder mBuilder;
	// 在其他地方移除通知时需要使用
	public static int notifyId = 1000;
	Notification messageNotification;
	ArrayList<Object> recordArray = new ArrayList<Object>();
	DBUtil dbUtil;
	DoctorReserveDetail mDetail;
	Context mContext;
	User mUser;

	@Override
	public void onReceive(final Context context, Intent intent) {

		this.mContext = context;
		if (dbUtil == null) {
			dbUtil = DBUtil.getInstance(context);
		}

		if (CommonUtility.isNull(mNotificationManager)) {
			mNotificationManager = (NotificationManager) context
					.getSystemService(Activity.NOTIFICATION_SERVICE);
			mBuilder = new NotificationCompat.Builder(context);

			PendingIntent pendingIntent = PendingIntent.getActivity(
					context,
					notifyId,
					new Intent(context, GlobalSettings
							.getActivity4Navigate(context)),
					Notification.FLAG_AUTO_CANCEL);

			mBuilder.setContentTitle("测试标题").setContentText("测试内容")
					.setContentIntent(pendingIntent)
					// .setNumber(number)//显示数量
					.setTicker("测试通知来啦")// 通知首次出现在通知栏，带上升动画效果的
					.setWhen(System.currentTimeMillis())// 通知产生的时间，会在通知信息里显示
					.setPriority(Notification.PRIORITY_DEFAULT)// 设置该通知优先级
					// .setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消
					.setOngoing(false)// ture，设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
					.setDefaults(Notification.DEFAULT_VIBRATE)// 向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置，使用defaults属性，可以组合：
					// Notification.DEFAULT_ALL Notification.DEFAULT_SOUND 添加声音
					// // requires VIBRATE permission
					.setSmallIcon(R.drawable.ic_launcher);

			/*
			 * PendingIntent contentIntent = PendingIntent.getActivity( context,
			 * notifyId, new Intent(context, GlobalSettings
			 * .getActivity4Navigate(context)),
			 * PendingIntent.FLAG_UPDATE_CURRENT);
			 * mBuilder.setContentIntent(contentIntent) //
			 * .setNumber(number)//显示数量 // .setTicker("测试通知来啦")//
			 * 通知首次出现在通知栏，带上升动画效果的 .setWhen(System.currentTimeMillis())//
			 * 通知产生的时间，会在通知信息里显示 .setAutoCancel(true)// 设置这个标志当用户单击面板就可以让通知将自动取消
			 * .setOngoing(false)//
			 * ture，设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐
			 * )或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
			 * .setDefaults(Notification.DEFAULT_VIBRATE)//
			 * 向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置，使用defaults属性，可以组合： //
			 * Notification.DEFAULT_ALL Notification.DEFAULT_SOUND 添加声音 // //
			 * requires VIBRATE permission
			 * .setSmallIcon(R.drawable.ic_launcher);
			 */
		}
		Bundle bundle = intent.getExtras();
		switch (bundle.getInt(PushConsts.CMD_ACTION)) {
		case PushConsts.GET_MSG_DATA:
			byte[] payload = bundle.getByteArray("payload");
			if (payload != null) {
				String data = new String(payload);

				if (data.contains("type\":\"reserve")) {
					// 预约
					try {
						ReserveCode code = JsonUtil.convert(data,
								ReserveCode.class);
						requestByHttpGet(code.reserveid);
					} catch (Exception e) {
						e.printStackTrace();
					}

				} else {
					try {
						JSONArray array = new JSONArray(data);
						JSONObject object = KeyValueUtil.get(array, "Type");
						int dataCode = object.getInt("Value");

						Log.i("testooo", "dataCode:" + dataCode);

						if (dataCode == 2001 || dataCode == 2003
								|| dataCode == 2004 || dataCode == 2005
								|| dataCode == 2006 || dataCode == 2007 || dataCode == 2008) {

							/**
							 * 医生资质审核 2006--成功 2007--失败 通知数据进行刷新
							 */

							object = KeyValueUtil.get(array, "content");
							mBuilder.setTicker(object.getString("Value"))
									.setContentTitle("皮肤科医生")
									.setContentText(object.getString("Value"));

							Intent resultIntent = new Intent(context,
									GlobalSettings
											.getActivity4Navigate(context));
							resultIntent
									.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

							Bundle bund = new Bundle();
							bund.putString("data", "123456");
							resultIntent.putExtras(bund);

							PendingIntent pendingIntent = PendingIntent
									.getActivity(context, 0, resultIntent,
											PendingIntent.FLAG_UPDATE_CURRENT);
							mBuilder.setContentIntent(pendingIntent);
							mNotificationManager.notify(notifyId,
									mBuilder.build());

							if (dataCode == 2006 || dataCode == 2007) {
								Intent shenhe = new Intent();
								shenhe.setAction(Constant.RECIVER_MYIFNO_SHENHE);

								if (dataCode == 2006) {
									shenhe.putExtra("shenhe", true);
								} else if (dataCode == 2007) {
									shenhe.putExtra("shenhe", false);
								}
								context.sendBroadcast(shenhe);
							}
							
							Log.i("testtip", "onReceiver.tip.datacode:" +  dataCode);
							
							
							if (dataCode == 2001 || dataCode == 2003 || dataCode == 2004) {
								TipMessageVo vo = new TipMessageVo();
								ContentValues values = new ContentValues();

								values.put("mId",
										KeyValueUtil.get(array, "question.qid")
												.getString("Value"));
								
								Log.i("testtip", "onReceiver.array:" + array);
								
								Log.i("testtip", "onReceiver.mId:" + KeyValueUtil.get(array, "question.qid")
												.getString("Value"));

								values.put("message", object.getString("Value"));

								JsonDate date = new JsonDate();
								date.setTime(System.currentTimeMillis());
								values.put("time", date.toString());
								values.put("messageType", dataCode);
								values.put("readState", 0);

								dbUtil.insert(
										TipMessageVo.class.getSimpleName(),
										values);

								Intent noInfo = new Intent();

								Intent noItem = new Intent();

								noInfo.setAction(Constant.RECIVER_MYIFNO_TAB_NOREAD);
								noInfo.putExtra("show", true);

								noItem.setAction(Constant.RECIVER_MYIFNO_ITEM_NOREAD);

								context.sendBroadcast(noInfo);
								context.sendBroadcast(noItem);

							}
							if (dataCode == 2003) {
								HashMap<String, Object> params = new HashMap<String, Object>();
								params.put(Constant.PARAM_API, "Question.Get");
								params.put("token", GlobalSettings.sToken);
								params.put("qids",
										KeyValueUtil.get(array, "question.qid")
												.getString("Value"));
								Intent finishChatData = new Intent(
										Constant.RECEIVER_CHATING);
								finishChatData.putExtra(
										Constant.IDENTITY_KEY_1, true);
								context.sendBroadcast(finishChatData);
								RequestTaskIntercept.requestIntercept(context,
										Constant.URL.REQUEST,
										new RequestHandler(context,
												new HandlerCallback() {

													@Override
													public void callback(
															Object o) {
														if (!CommonUtility
																.isNull(o)) {
															try {
																JSONObject question = (JSONObject) o;
																question = question
																		.getJSONArray(
																				Constant.JSON_PARAM_RES)
																		.getJSONObject(
																				0);
																Intent freshSessionlistData = new Intent(
																		Constant.RECIVER_CHAT_FINISH_REFRESH);
																freshSessionlistData
																		.putExtra(
																				Constant.IDENTITY_KEY,
																				question.toString());
																context.sendBroadcast(freshSessionlistData);
															} catch (Exception e) {
																e.printStackTrace();
															}
														}
													}
												}), params);
							}

						} else if (/* dataCode == 2002 || */dataCode == 3000) {

							object = KeyValueUtil.get(array, "sender.uid");

							if (dbUtil == null) {
								dbUtil = DBUtil.getInstance(context);
							}
							recordArray.clear();
							int uid = object.getInt("Value");
							ArrayList<CacheCommon> caches = dbUtil.queryCache(
									ChatActivity.class.getSimpleName(), uid);

							if (caches.size() > 0) {
								String datas = caches.get(0).data;
								try {
									JSONArray arrays = new JSONArray(datas);
									CommonUtility.putAll(recordArray, arrays,
											true);

								} catch (Exception e) {
									e.printStackTrace();
								}
							}

							if (object.getInt("Value") != ChatActivity.currentQid) {
								mBuilder.setTicker("您收到新的会话")
										.setContentTitle("蜜肤")
										.setContentText("您收到新的会话");
								mNotificationManager.notify(notifyId,
										mBuilder.build());
							} else {
								DeviceUtility.DeviceController.Vibrate(context,
										500);
							}
							object = new JSONObject(KeyValueUtil.get(array,
									"content").getString("Value"));

							object.put("readState", false);

							recordArray.add(0, object);

							ChatActivity.put2Cache(recordArray, uid);

							Intent d = new Intent(Constant.RECEIVER_CHATING);
							d.putExtra(Constant.IDENTITY_KEY, array.toString());
							context.sendBroadcast(d);

							Intent refreshIntent = new Intent(
									Constant.RECIVER_SESSION_TAB_NOREAD);
							refreshIntent.putExtra("uid", uid + "");
							context.sendBroadcast(refreshIntent);
							
							Log.i("testreceiverpoint", "xxxxxx");
							
						}

						Intent chatListData = new Intent(
								Constant.RECIVER_CHAT_LIST);
						context.sendBroadcast(chatListData);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
			break;
		case PushConsts.GET_CLIENTID:
			// 获取ClientID(CID)
			// 第三方应用需要将CID上传到第三方服务器，并且将当前用户帐号和CID进行关联，以便日后通过用户帐号查找CID进行消息推送
			String cid = bundle.getString("clientid");
			if (GlobalSettings.sToken != null) {
				UserSetRequest req = new UserSetRequest();
				req.token = GlobalSettings.sToken;
				req.GT_ClientID = cid;
				UserSetTask task = new UserSetTask();
				task.setRequest(req);
				task.setContext(context);
				task.start();
			}
			break;
		}
	}

	public void notifyreserve() {
		String ns = Context.NOTIFICATION_SERVICE;
		NotificationManager mNotificationManager = (NotificationManager) mContext
				.getSystemService(ns);
		int icon = R.drawable.ic_launcher;
		CharSequence tickerText = "您预约项目(" + mDetail.name + ")"
				+ mDetail.status;
		long when = System.currentTimeMillis();
		Notification notification = new Notification(icon, tickerText, when);
		notification.flags = Notification.FLAG_INSISTENT;
		notification.flags = Notification.FLAG_ONGOING_EVENT;
		// notification.flags = Notification.DEFAULT_ALL;
		// notification.defaults |= Notification.DEFAULT_VIBRATE;
		CharSequence contentTitle = tickerText;
		Intent notificationIntent = new Intent(mContext,
				MyTreatmentProjectActivity.class);
		// notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		DoctorReserveItem item = new DoctorReserveItem();
		item.id = mDetail.id;
		item.hospital = mDetail.hospital;
		item.name = mDetail.name;
		item.status = mDetail.status;
		item.discount_price = mDetail.discount_price;
		item.reserve_no = mDetail.reserve_no;
		item.url = mDetail.url;
		TreatementProjectExtra extra = new TreatementProjectExtra();
		extra.setUser(item);
		RemoteViews remoteView = new RemoteViews(mContext.getPackageName(),
				R.layout.treatment_notify);
		remoteView.setTextViewText(R.id.title, tickerText);
		// notification.contentView = remoteView;
		if (extra.putTo(notificationIntent)) {
			PendingIntent contentIntent = PendingIntent.getActivity(mContext,
					0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
			// notification.contentIntent = contentIntent;
			notification.setLatestEventInfo(mContext, contentTitle, "",
					contentIntent);

			mNotificationManager.notify(1, notification);
		}
	}

	public void requestByHttpGet(final int id) {
		new Thread() {
			public void run() {

				String path = GlobalSettings.SERVER_URL_TREATMENT
						+ "Client/DoctorReserve/reserveInfo/reserveid/" + id;
				// 新建HttpGet对象
				HttpGet httpGet = new HttpGet(path);
				// 获取HttpClient对象
				HttpClient httpClient = new DefaultHttpClient();
				// 获取HttpResponse实例
				try {
					HttpResponse httpResp = httpClient.execute(httpGet);
					// 判断是够请求成功
					if (httpResp.getStatusLine().getStatusCode() == 200) {
						// 获取返回的数据
						String result = EntityUtils.toString(
								httpResp.getEntity(), "UTF-8");
						if (result != null && !result.trim().equals("")) {
							DoctorReserveDetailResponse res = JsonUtil.convert(
									result, DoctorReserveDetailResponse.class);
							if (res != null && res.size() > 0) {
								mDetail = res.get(0);
								if (mDetail.status.equals("已消费")) {
									loadDoctor(mDetail.doctor_id + "");

								} else if (mDetail.status.equals("已确认")) {
									notifyreserve();
								} else if (mDetail.status.contains("取消")) {
									notifyreserve();
								}
							}
						}

					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			};
		}.start();
	}

	public void loadDoctor(String uid) {
		String url = GlobalSettings.SERVER_URL + GlobalSettings.SERVER_URL_JOIN
				+ "?api=User.Get&appname=" + Constant.APP_NAME + "&uids=" + uid;
		HttpGet httpGet = new HttpGet(url);
		// 获取HttpClient对象
		HttpClient httpClient = new DefaultHttpClient();
		// 获取HttpResponse实例
		try {
			HttpResponse httpResp = httpClient.execute(httpGet);
			// 判断是够请求成功
			if (httpResp.getStatusLine().getStatusCode() == 200) {
				// 获取返回的数据
				String result = EntityUtils.toString(httpResp.getEntity(),
						"UTF-8");
				if (result != null && !result.trim().equals("")) {
					mUser = JsonUtil.convert(result, User.class);
					notifyreserve();
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static class ReserveCode implements INoProguard {
		public int reserveid;
		public String type;
		public String status;
	}

}
// 推送消息格式：[{"reserveid"=>"1111","type"=>"reserve","status"=>"已确认"}]
// 医生接单
// [{"Key":"Type","Value":"2001"},{"Key":"patient.uid","Value":"1"},{"Key":"doctor.uid","Value":"2"},{"Key":"question.qid","Value":"3"},{"Key":"content","Value":"《医院名字》的《医生名字》大夫接单了您的问题"}]
// 问题被解答
// [{"Key":"Type","Value":"2003"},{"Key":"patient.uid","Value":"1"},{"Key":"doctor.uid","Value":"2"},{"Key":"question.qid","Value":"3"},{"Key":"content","Value":"您的问题已被解答，请查看"}]
// 付费咨询
// [{"Key":"Type","Value":"2004"},{"Key":"patient.uid","Value":"1"},{"Key":"doctor.uid","Value":"2"},{"Key":"question.qid","Value":"3"},{"Key":"content","Value":"患者《病人名字》向您发起了付费咨询，请查看"}]
// 会话消息
// [{"Key":"Type","Value":"2002"},{"Key":"patient.uid","Value":"264"},{"Key":"receiver.uid","Value":"265"},{"Key":"question.qid","Value":"40"},{"Key":"content","Value":"{"id":"0016320140728103542731000","Qid":163,"Uid":264,"Receive_Uid":110,"CreateTime":"2014-07-28T10:35:42.731+08:00","User_Type":1,"Content":"内容user10353374","Pic":["pic1","pic210353374"],"Session_Type":0,"Aid":0,"Is_Received":0,"FilePath":""}"}]

// [{"Key":"Type","Value":"2005"},{"Key":"patient.uid","Value":"5"},{"Key":"doctor.uid","Value":"4"},{"Key":"question.qid","Value":"71"},{"Key":"question.cost","Value":"0"},{"Key":"content","Value":"您解答的问题已被评价[question.cost.desc]。问题摘要“最近身体不太舒服，请…”"}]

// 通知数据
// 2004：收到付费咨询
// 2004是原有的逻辑 修改了描述文字
// 以下为新增
// 2005：收到评价/收到解答费用 （如果是付费 则有解答费用的描述）
// 2006/7：资质审核通过、拒绝
// 2008：提现审核通过
